//
//  JPayController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/5.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JPayController.h"

#import "JPayHeadView.h"
#import "JPayMidView.h"
#import "JPayWayView.h"
@interface JPayController ()

@property (nonatomic , strong) UILabel *totlePriceLabel;

@property (nonatomic, assign) CGFloat lastMay;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) JPayHeadView *headView;
@property (nonatomic, strong) JPayWayView *buttomView;

@property (nonatomic, strong) NSMutableArray *midViewMarr;

@property (nonatomic, copy) NSArray *dataArray;
@property (nonatomic, strong) JAddressModel *addressModel;

@end

@implementation JPayController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [super InitUI];
    self.titleLabel.text = @"确认订单";
    self.leftButton.hidden = NO;
    self.rightButton.hidden = YES;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.contentView.backgroundColor = kRGBColor(245, 245, 245);
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    _dataArray = [NSArray array];
    _midViewMarr = [NSMutableArray array];
    [self loadAddressRequest];
//    [self loadData];
    [self configView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
}

#pragma mark - 键盘监听
- (void)keyboardWillShow:(NSNotification *)note {
         
     CGRect keyboardBounds;
     [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
     NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
     NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
     
     // Need to translate the bounds to account for rotation.
     keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
     
     // 动画改变位置
     [UIView animateWithDuration:[duration doubleValue] animations:^{
         [UIView setAnimationBeginsFromCurrentState:YES];
         [UIView setAnimationDuration:[duration doubleValue]];
         [UIView setAnimationCurve:[curve intValue]];
         // 更改输入框的位置
         
         self.scrollView.frame = CGRectMake(0, self.scrollView.origin.y - 70, kWindowW, self.scrollView.height);
         
     }];
 }
     
- (void)keyboardWillHide:(NSNotification *)note {
         
     NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
     NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
     
     // 动画改变位置
     [UIView animateWithDuration:[duration doubleValue] animations:^{
         [UIView setAnimationBeginsFromCurrentState:YES];
         [UIView setAnimationDuration:[duration doubleValue]];
         [UIView setAnimationCurve:[curve intValue]];
         // 更改输入框的位置
         self.scrollView.frame = CGRectMake(0, 0, kWindowW, CGRectGetHeight(self.contentView.frame) - 49);
     }];
 }
     
- (void)configView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, CGRectGetHeight(self.contentView.frame) - 49)];
    [self.contentView addSubview:_scrollView];
    
    
    _headView = [[JPayHeadView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, 90) isHaveTap:YES];
    [_scrollView addSubview:_headView];
    
    [self setupCustomBottomView];
    
}

- (void)configMidView:(NSArray *)arr {
    _lastMay = 100;
        for (int i = 0; i < arr.count; i++) {
            JPayMidView *midView = [[JPayMidView alloc]initWithShopModel:arr[i]];
            CGFloat height = [midView getHeight];
            midView.frame = CGRectMake(0, _lastMay , kWindowW, height);
            [_scrollView addSubview:midView];
            [_midViewMarr addObject:midView];
            
            midView.textFieldBlock = ^(NSString *textStr) {
                NSLog(@"购买用户留言===%@",textStr);
            };
            _lastMay = _lastMay + height + 10;
        }
    
    _buttomView = [[JPayWayView alloc]initWithFrame:CGRectMake(0, _lastMay, kWindowW, 80)];
    [_scrollView addSubview:_buttomView];
    
    _buttomView.isHideNameBlock = ^(BOOL isHideName) {
        NSLog(@"是否匿名=====%d",isHideName);
    };
    
    [self sumScrollViewHeight];
}

#pragma mark -- 自定义底部视图
- (void)setupCustomBottomView {
    
    UIView *backgroundView = [[UIView alloc]init];
    backgroundView.backgroundColor = kRGBColor(245, 245, 245);
    [self.contentView addSubview:backgroundView];
    backgroundView.frame = CGRectMake(0, CGRectGetHeight(self.contentView.frame) -  49, kWindowW , 49);
    
    
    UIView *lineView = [[UIView alloc]init];
    lineView.frame = CGRectMake(0, 0, kWindowW, 1);
    lineView.backgroundColor = [UIColor lightGrayColor];
    [backgroundView addSubview:lineView];
    
    //结算按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.backgroundColor = [UIColor redColor];
    btn.frame = CGRectMake(kWindowW - 100, 0, 100, 49);
    [btn setTitle:@"提交" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(goToPayButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [backgroundView addSubview:btn];
//    self.allCountButton = btn;
    //合计
    UILabel *label = [[UILabel alloc]init];
    label.font = [UIFont systemFontOfSize:16];
    label.textColor = [UIColor redColor];
    [backgroundView addSubview:label];
    label.textAlignment = NSTextAlignmentRight;
    label.attributedText = [self DWQSetString:@"¥0.00"];
    CGFloat maxWidth = kWindowW - btn.bounds.size.width - 30;
    label.frame = CGRectMake(kWindowW - maxWidth - 10 - 5 - btn.bounds.size.width, 0, maxWidth - 10, 49);
    self.totlePriceLabel = label;
}

#pragma mark -
/*
 *
 *  计算已选中商品金额
 */
-(void)countPrice {
    double totlePrice = 0.0;
    NSInteger num = 0;
    
    for (JShopCarShopModel *model in self.dataArray) {
        for (JShopCarDetailModel *model2 in model.goodsArray) {
            totlePrice += model2.CustomerEnteredPrice * model2.Quantity;
            num += model2.Quantity;
        }
    }
    
    NSString *string = [NSString stringWithFormat:@"￥%.2f",totlePrice];

    self.totlePriceLabel.attributedText = [self DWQSetString:string];
}

- (NSMutableAttributedString*)DWQSetString:(NSString*)string {
    
    NSString *text = [NSString stringWithFormat:@"合计:%@",string];
    NSMutableAttributedString *DWQString = [[NSMutableAttributedString alloc]initWithString:text];
    NSRange rang = [text rangeOfString:@"合计:"];
    [DWQString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:rang];
    [DWQString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:rang];
    return DWQString;
}

- (void)sumScrollViewHeight
{
    JPayMidView *midView = _midViewMarr.lastObject;
    CGFloat height = midView.bottom + 90 ;
    _scrollView.contentSize = CGSizeMake(kWindowW, height);
}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setProductIDs:(NSString *)productIDs
{
    _productIDs = productIDs;
    [self loadData];
}

#pragma mark - loadRequest
/// 加载购物车 商品列表
- (void)loadData {
    
    [SVProgressHUD show];
    NSString *url = @"ShoppingCartItems/GetShoppingCartItems";
    
    NSString *productid;
    if (self.productIDs.length <= 0) {
        productid = nil;
    }
    else
    {
        productid = self.productIDs;
    }
    
    [JNetManager GetShopCarProductListUrl:url
                               productIDs:productid
                                   userID:[GLOBALDATA userInfoModel]
                                  success:^(id response) {
                                      if (response) {
                                          NSArray *arr = (NSArray *)response;
                                          if (arr.count > 0) {
                                              self.dataArray = [NSMutableArray arrayWithArray:arr];
                                              
                                              dispatch_async(dispatch_get_main_queue(), ^{
                                                  // 设置中间View
                                                  [self configMidView:arr];
                                              });
                                              
                                              // 显示合计金额
                                              [self countPrice];
                                              
                                          }
                                          [SVProgressHUD dismiss];

                                      }
                                  } failure:^(NSString *err) {
                                      [SVProgressHUD dismiss];
                                      [SVProgressHUD showErrorWithStatus:err];
                                  }];
    

}
// 获取地址
- (void)loadAddressRequest
{
    NSString *url = @"Address/GetAddress";
    
    [JNetManager getAddressRequestUrl:url
                           CustumerID:[GLOBALDATA userInfoModel].CustomerId
                              success:^(id response) {
                                  if (response) {
                                      self.addressModel = response;
                                      _headView.addressModel = self.addressModel;
                                  }
                              } failure:^(NSString *err) {
                                  [SVProgressHUD showErrorWithStatus:err];
                              }];
    
}

#pragma mark --- 确认选择,提交订单按钮点击事件
- (void)goToPayButtonClick:(UIButton*)button {
  
    [SVProgressHUD showSuccessWithStatus:@"前去付款"];
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
